﻿(function ($) {

    $.fn.extend({
        //pass the options variable to the function
        mobilejuniorchatbox: function (options) {

            //Set the default values, use comma to separate the settings, example:
            var defaults = {
                user_id: -1,
            };
            var myOptions = $.extend(defaults, options);

            var me = this;

            this.user_id = -1;
            if ($.cookie('user-id') != null) {
                this.user_id = $.cookie('user-id');
                $("#ChatSection").show();
                $("#LogInSection").hide();
                $("#selectorError").hide();
                $.removeCookie('user-id');
            }

            this.find('#UserName').bind("keyup change", function () { EnableDisable(me, "#UserName", "#LogIn"); });
            this.find('#UserInput').bind("keyup change", function () { EnableDisable(me, "#UserInput", "#Send"); });


            this.find('#UserName').keypress(function (e) {
                if (e.which == 13)
                    DoLogIn(me);
            });
            this.find('#UserInput').keypress(function (e) {
                if (e.which == 13)
                    SendMessage(me);
            });
            this.find("#LogIn").click(function () {
                DoLogIn(me);
            });

            this.find("#Send").click(function () {
                SendMessage(me);
            });

            doPoll(me);
            
            initialize(me);
            $("#aboutMobilePage").on('pageload', function() {
                initialize(me);
                $('#map-canvas').listview("refresh", "true");
            });

            return this;
        },
        juniorregister: function (options) {

            //Set the default values, use comma to separate the settings, example:
            var defaults = {
            };
            var myOptions = $.extend(defaults, options);

            var me = this;

            this.find("#Register").click(function () {
                doRegister(me);
            });

            getImages(me);

            //validation
            this.find('#Name,#NickName').bind("keyup change", function () { EnableDisable(me, "#Name,#NickName", "#Register"); });


            //var myObject = new JuniorChatBox();
        }
    });
    function doRegister(control) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                register(control, position);
            }, error);
        } else {
            error('not supported');
        }
    }
    function register(control, position) {
        var pos = {};
        pos.Latitude = position.coords.latitude;
        pos.Longitude = position.coords.longitude;

        var data = {
            name: control.find("#Name").val(),
            nickname: control.find("#NickName").val(),
            iconUrl: control.find('input[name=Icon]:checked').val(),
            //    position:pos

        };
        $.ajax({
            url: "/ChatBox/Register",
            data: data,
            type: "POST",
            dataType: "json"
        }).done(function (data) {
            $.cookie('user-id', data, { path: "/" });
            var l = window.location;
            window.location = l.protocol + "//" + l.host;
        });
    }

    function getImages(control) {
        var img = control.find("#images");
        $.ajax({
            url: "/ChatBox/GetImages",
            type: "GET",
            dataType: "json"
        }).done(function (data) {

            for (el in data) {
                img.append("<div class=\"char-icon\"><input type=\"radio\" name=\"Icon\" value=\"" + data[el].toString() + "\" /><img src=\"../../Content/img/characters/" + data[el].toString() + "\"/></div>");
            }

        });
    }

    function EnableDisable(control, field, button) {
        var emptyFields = control.find(field).filter(
            function () {
                return this.value === "";
            }
        );
        if (!emptyFields.length) {
            control.find(button).removeAttr("disabled").button('refresh');
        } else {
            control.find(button).attr("disabled", "disabled").button('refresh');
        }
    }

    function error(msg) {
        var s = document.querySelector('#status');
        s.innerHTML = typeof msg == 'string' ? msg : "failed";
        s.className = 'fail';

        // console.log(arguments);
    }

    function success(control, position) {
        var pos = {};
        pos.Latitude = position.coords.latitude;
        pos.Longitude = position.coords.longitude;
        var data = JSON.stringify({
            Name: control.find("#UserName").val(),
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
            //position: pos
        });

        $.ajax({
            url: "/ChatBox/LogIn",
            data: data,
            type: "POST",
            contentType: "application/json",
            dataType: "json"
        }).done(function (data) {
            if (data > 0) {
                control.user_id = data;
                control.find("#ChatSection").show();
                control.find("#LogInSection").hide();
                control.find("#selectorError").hide();
                //control.find("#mainMobilePage").trigger('create');
            } else {
                control.find("#selectorError").show();
                control.find("#UserName").val("");
                //control.find("#mainMobilePage").trigger('create');
            }
        });
    }

    function DoLogIn(control) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                success(control, position);
            }, error);
        } else {
            error('not supported');
        }


    }

    function SendMessage(control) {
        var data = {
            id: control.user_id,
            message: control.find("#UserInput").val()
        };

        $.ajax({
            url: "/ChatBox/SendMessage",
            data: data,
            type: "POST",
            dataType: "json"
        }).done(function (data) {
            control.find("#UserInput").val("");
        });
    }

    function doPoll(control) {
        getUserList(control);
        if (control.user_id != -1) {
            getMessageList(control);
        }
        setTimeout(function () {
            doPoll(control);
        }, 2000);
    }

    function getUserList(control) {
        $.ajax({
            url: "/ChatBox/GetList",
            type: "GET",
            dataType: "json"
        }).done(function (data) {
            var htmlOutput = $("#user").render(data);
            $("#LoggedInUsersContainer").html(htmlOutput);
            $("#LoggedInUsersContainer").listview("refresh", "true");


        });
    }

    function getMessageList(control) {
        $.ajax({
            url: "/ChatBox/GetLastMessages",
            data: { id: control.user_id },
            type: "GET",
            dataType: "json"
        }).done(function (data) {
            var htmlOutput = $("#message").render(data);
            $("#MessagesContainer").html(htmlOutput);
            $("#MessagesContainer").listview("refresh", "true");

        });
    }
    
    function getMapUserList(control) {
        $.ajax({
            url: "/ChatBox/GetList",
            type: "GET",
            dataType: "json"
        }).done(function (data) {
            
            $('#map-canvas').gmap().bind('init', function (ev, map) {
                $.each(data, function () {
                    //add_marker(map, this.Name, this.Position.Latitude, this.Position.Longitude, this.IconUrl);
                    $('#map-canvas').gmap('addMarker', { 'position': this.Position.Latitude + ',' + this.Position.Longitude, 'bounds': true,  icon : 'Content/img/'+this.IconUrl }).click(function () {
                        $('#map-canvas').gmap('openInfoWindow', { 'content': this.Name }, this);
                    });
                });
                
            });
            $.each(data, function () {
                add_marker(map, this.Name, this.Position.Latitude, this.Position.Longitude, this.IconUrl);
            });
        });
    }

    function initialize(control) {
        google.maps.visualRefresh = true;
        getMapUserList(control);
    }

    function add_marker(map, user, lat, lon, image) {
        var myLatlng = new google.maps.LatLng(lat, lon);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: user,
            icon: image
        });
    }





}(jQuery));

